package com.app.utiles.sound;

import android.media.MediaPlayer;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;

import com.app.utiles.other.DLog;
import com.app.utiles.other.FileUtile;
import com.app.utiles.other.ToastUtile;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;

// 播放声音
public class MediaManager {
    //  播放器
    private MediaPlayer mediaPlayer;
    private static MediaManager mediaManager;
    private MediaPlayerListener mediaPlayerListener;
    private String url, path;

    private MediaManager() {
        mediaPlayer = new MediaPlayer();
        mediaPlayerListener = new MediaPlayerListener();
        mediaPlayer.setOnPreparedListener(mediaPlayerListener);
        mediaPlayer.setOnCompletionListener(mediaPlayerListener);
        mediaPlayer.setOnErrorListener(mediaPlayerListener);
        playHandler = new PlayHandler();
    }

    //  获取实例
    public static MediaManager getInstance() {
        if (mediaManager == null) {
            mediaManager = new MediaManager();
        }
        return mediaManager;
    }


    public void playMusic(String soundUrl, String soundPath) {
        playMusic(soundUrl, soundPath, 0);
    }

    /**
     * 播放语音
     *
     * @param soundUrl  声音url
     * @param soundPath 本地声音path
     * @param seekTo    播放起始位置
     */
    public void playMusic(String soundUrl, String soundPath, int seekTo) {

        //没有声音文件
        if (TextUtils.isEmpty(soundUrl) && TextUtils.isEmpty(soundPath)) {
            return;
        }
        try {
            closeMusic();
            url = soundUrl;
            path = soundPath;
            if (!TextUtils.isEmpty(soundPath) && new File(soundPath).exists()) {
                // 录音的文件存在 -就直接用它
                FileInputStream fis = new FileInputStream(soundPath);
                mediaPlayer.setDataSource(fis.getFD());
                mediaPlayer.prepareAsync();
                return;
            }
            //判断音频是否下载，可用
            String path = FileUtile.getVoiceCacheFileName(soundUrl);
            if (!TextUtils.isEmpty(path) && new File(path).exists()) {
                File file = new File(path);
                FileInputStream fis = new FileInputStream(file);
                mediaPlayer.setDataSource(fis.getFD());
                mediaPlayer.prepareAsync();
                return;
            }
            //使用网络音频
            mediaPlayer.setDataSource(soundUrl);
            mediaPlayer.prepareAsync();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    //设置播放进度
    public boolean seekToMusic(int seekTo) {
        if (mediaPlayer == null) {
            return false;
        }
        if (!mediaPlayer.isPlaying()) {
            return false;
        }
        mediaPlayer.seekTo(seekTo);
        mediaPlayer.start();
        return true;
    }

    public boolean isPlaying() {
        if (mediaPlayer == null) {
            return false;
        }
        return mediaPlayer.isPlaying();
    }

    // 正在播放的停止播放
    public void closeMusic() {
        if (mediaPlayer == null) {
            return;
        }
        if (!mediaPlayer.isPlaying()) {
            return;
        }
        mediaPlayer.stop();
        mediaPlayer.reset();
        playHandler.removeMessages(WHAT_PLAY);
        DLog.e("播放", "完成");
        if (TextUtils.isEmpty(url) && TextUtils.isEmpty(path)) {
            return;
        }
        int size = listeners.size();
        if (size == 0) {
            return;
        }
        listeners.get(size - 1).onPlayStop(url, path);
    }


    //关闭activitty
    public void onDestroy() {
        url = "";
        path = "";
        closeMusic();
        removeOnMediaListener();
    }

    //播放监听
    class MediaPlayerListener implements MediaPlayer.OnCompletionListener, MediaPlayer.OnErrorListener,
            MediaPlayer.OnPreparedListener {

        @Override
        public void onCompletion(MediaPlayer mp) {
            url = "";
            path = "";
            //播放完成
            mediaPlayer.stop();
            mediaPlayer.reset();
            playHandler.removeMessages(WHAT_PLAY);
            DLog.e("播放", "完成");
            int size = listeners.size();
            if (size == 0) {
                return;
            }
            listeners.get(size - 1).onCompletion(mp);
        }

        @Override
        public boolean onError(MediaPlayer mp, int what, int extra) {
            boolean isPlaying = mp.isPlaying();
            playHandler.removeMessages(WHAT_PLAY);
            if (!isPlaying) {
                ToastUtile.showToast("播放错误");
            }
            DLog.e("播放", "播放错误");
            int size = listeners.size();
            if (size != 0) {
                listeners.get(size - 1).onError(mp, what, extra);
            }
            return false;
        }

        @Override
        public void onPrepared(MediaPlayer mp) {
            //播放准备
            mediaPlayer.start();
            playHandler.removeMessages(WHAT_PLAY);
            playHandler.sendEmptyMessageDelayed(WHAT_PLAY, WHAT_PLAY_TIME);
            DLog.e("播放", "播放开始");
            int size = listeners.size();
            if (size == 0) {
                return;
            }
            listeners.get(size - 1).onPrepared(mp);
        }
    }

    private ArrayList<OnMediaListener> listeners = new ArrayList<>();
    private ArrayList<Boolean> progress = new ArrayList<>();

    public void setAddOnMediaListener(OnMediaListener onMediaListener) {
        setAddOnMediaListener(onMediaListener, false);
    }

    /**
     * 添加监听
     *
     * @param onMediaListener
     * @param isProgress      true 返回播放进度
     */
    public void setAddOnMediaListener(OnMediaListener onMediaListener, boolean isProgress) {
        listeners.add(onMediaListener);
        progress.add(isProgress);
    }

    //移除监听
    public void removeOnMediaListener() {
        int size = listeners.size();
        if (size == 0) {
            return;
        }
        listeners.remove(size - 1);
        progress.remove(size - 1);
    }

    private PlayHandler playHandler;
    private final int WHAT_PLAY = 1;
    private final int WHAT_PLAY_TIME = 1 * 1000;

    //今天进度的Handler
    class PlayHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);


            int size = listeners.size();
            if (size == 0) {
                return;
            }
            Boolean isProgress = progress.get(0);
            if (isProgress == null || !isProgress) {
                removeMessages(WHAT_PLAY);
                return;
            }
            int playLength = mediaPlayer.getDuration();
            int playProgress = mediaPlayer.getCurrentPosition();
            listeners.get(0).onPlayProgress(playProgress, playLength);
            sendEmptyMessageDelayed(WHAT_PLAY, WHAT_PLAY_TIME);
        }
    }

    //声音播放监听
    public interface OnMediaListener {
        void onCompletion(MediaPlayer mp);

        void onError(MediaPlayer mp, int what, int extra);

        void onPrepared(MediaPlayer mp);

        //播放进度条
        void onPlayProgress(int playProgress, int playLength);

        //暂停
        void onPlayStop(String url, String path);
    }
}
